package castledefense.logic.buildings;

import castledefense.data.BuildingData;
import castledefense.data.GameData;
import castledefense.game.screens.MainGameScreen;
import castledefense.logic.Map;
import castledefense.logic.Targetable;

public class Tower1 extends ElementBuilding {
	protected int timeBetweenAttack = 1 * 1000;
	protected int timeBeforeNextAttack = timeBetweenAttack;
	protected int timeAttacking = 500;
	protected int timeBeforeAttackEnds = 0;
	protected double range = 8;
	protected double damage = 3;
	protected boolean attacking;
	protected Targetable target;
	private Map map;

	public Tower1(Map map, int posX, int posY, int type) {
		super(map, posX, posY, 2, type);
		size = 2;
		cost = BuildingData.tower1Cost;
		elementType = GameData.noElement;
	}

	public double getDamage() {
		return damage;
	}

	public int getRange() {
		return (int) range;
	}

	public void setMap(Map map) {
		this.map = map;
	}

	public void update(int deltaTime) {
		timeBeforeNextAttack -= deltaTime;
		if (timeBeforeNextAttack < 0) {
			timeBeforeNextAttack = timeBetweenAttack;
			attack();
			attacking = true;
			timeBeforeAttackEnds = timeAttacking;
		}

		timeBeforeAttackEnds -= deltaTime;
		if (timeBeforeAttackEnds < 0)
			attacking = false;
	}

	private void attack() {
		if (target == null || !target.isLife() || !isInRange(target)) {
			target = map.getNearestUnit(getCenterX(), getCenterY(), range);
		}

		if (target != null) {
			int tmpLvl = 0;
			if (elementType != -1) {
				tmpLvl = upgradeLevel[elementType];
			}

			MainGameScreen.missileSystem.createMissile(target, getCenterX(),
					getCenterY(), damage, elementType, tmpLvl);
		}
	}

	private boolean isInRange(Targetable target2) {
		final double dx = target2.getCenterX() - this.getCenterX();
		final double dy = target2.getCenterY() - this.getCenterY();
		return (dx * dx + dy * dy) < (range * range);
	}

}
